package com.easemob.helpdesk.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.easemob.helpdesk.adapter.TagAdapter;
import com.easemob.helpdesk.bean.LevelBean;
import com.easemob.helpdesk.bean.ListTagBean;
import com.easemob.helpdesk.bean.TagListItemBean;
import com.easemob.helpdesk.bean.TagBean;
import com.easemob.helpdesk.widget.SpaceItemDecoration;
import com.easemob.helpdesk.widget.SwipeItemLayout;
import com.housekeeperapp.R;
import com.net.ApiService;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import java.util.ArrayList;
import java.util.List;


import retrofit2.Call;

/**
 * Created by xiaolong.wei on 2019/4/3.
 */

public class TagsActivity extends BaseActivityV2 implements TagAdapter.OnDeleteItemListener{

    private static final String TAG = "TagsActivity";

    @Override
    protected void initFindView() {

        mRecyclerView=findViewById(R.id.recycler_view);

        empty_tag=findViewById(R.id.empty_tag);
        levelTextView=findViewById(R.id.level);

        detailLevelTextView=findViewById(R.id.detail_level);

        findViewById(R.id.back).setOnClickListener(view -> {
            dismissAddTagDialog();
            dismissDeleteTagDialog();
            setResult(RESULT_OK);
            finish();
        });
        findViewById(R.id.add_tag_button).setOnClickListener(view -> {
            if (addTagDialog == null){
                initAddTagDialog();
            }
            addTagDialog.show();
        });

        levelTextView.setOnClickListener(view -> {
            if (pickerView == null && levelDataSource != null && levelDataSource.size() > 0){
                initDistrictPopupWindow();
                pickerView.show();
            }else if (pickerView != null && !pickerView.isShowing()){
                pickerView.show();
            }else {
                Toast.makeText(this,"暂无等级信息",Toast.LENGTH_LONG);
            }

        });

        detailLevelTextView.setOnClickListener(view -> {
            if (pickerView == null && levelDataSource != null && levelDataSource.size() > 0){
                initDistrictPopupWindow();
                pickerView.show();
            }else if (pickerView != null && !pickerView.isShowing()){
                pickerView.show();
            }else {
                Toast.makeText(this,"暂无等级信息",Toast.LENGTH_LONG);
            }
        });

    }

    RecyclerView mRecyclerView;
    TextView empty_tag;
    TextView levelTextView;
    TextView detailLevelTextView;

    private TagAdapter mAdatper;
    private ListTagBean mListTagBean;
    private List<TagListItemBean> tagListItemBeans;

    private int lastX;
    private int lastY;


    Dialog addTagDialog;
    Dialog deleteTagDialog;
    private TextView deleteTagTextView;

    private long ownerId;

    RadioGroup radioGroup;
    EditText inputTag;

    private String deleteType;
    private String deleteTag;
    private int deletePosition;

    private String levelKey;
    private String detailLevelKey;

    PopupWindow mPopupWindow;
    private List<LevelBean> levelDataSource;

    private LevelBean selectLevel;
    private LevelBean selectDetailLevel;

    OptionsPickerView pickerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tags_activity);
        initFindView();
        Intent intent = getIntent();
        ownerId = intent.getLongExtra("OWNER_ID",-1L);

        String l = intent.getStringExtra("levelValue");
        String dl = intent.getStringExtra("detailLevelValue");
        levelTextView.setText(TextUtils.isEmpty(l)?"暂无等级":l);
        detailLevelTextView.setText(TextUtils.isEmpty(dl)?"暂无细分等级":dl);
        levelKey = intent.getStringExtra("levelKey");
        detailLevelKey = intent.getStringExtra("detailLevelKey");


        tagListItemBeans = new ArrayList<>();

        mRecyclerView.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(this));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(2));
        mAdatper = new TagAdapter(this,tagListItemBeans);
        mAdatper.setListener(this);
        mRecyclerView.setAdapter(mAdatper);

        getTagList();
        getLevelDataSource();
    }

    private void initAddTagDialog(){
        addTagDialog = new Dialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.add_tag_dialog, null);

        radioGroup = (RadioGroup) contentView.findViewById(R.id.radio_group);
        inputTag = contentView.findViewById(R.id.input_tag);
        InputFilter inputFilter = new InputFilter.LengthFilter(10);
        InputFilter[] i = {inputFilter};
        inputTag.setFilters(i);

        addTagDialog.setContentView(contentView);
        addTagDialog.setCanceledOnTouchOutside(false);
        addTagDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        contentView.findViewById(R.id.close_dialog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissAddTagDialog();
            }
        });
        contentView.findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
                String selectTagType = "";
                if (checkedRadioButtonId == R.id.food_hobby){
                    selectTagType = "饮食喜好";
                }else if (checkedRadioButtonId == R.id.life_habit){
                    selectTagType = "生活习惯";
                }else if (checkedRadioButtonId == R.id.speciality_interest){
                    selectTagType = "特长爱好";
                }else if (checkedRadioButtonId == R.id.pet_status){
                    selectTagType = "养宠状态";
                }else if (checkedRadioButtonId == R.id.other){
                    selectTagType = "其他";
                }else {
                    selectTagType = "";
                }
                if (TextUtils.isEmpty(selectTagType)){
                    Toast.makeText(TagsActivity.this,"请选择分类标签",Toast.LENGTH_LONG).show();
                    return;
                }
                String tag = inputTag.getText().toString();
                if (TextUtils.isEmpty(tag)){
                    Toast.makeText(TagsActivity.this,"请输入标签",Toast.LENGTH_LONG).show();
                    return;
                }

                addTag(selectTagType,tag);
            }
        });


    }

    private void getLevelDataSource(){
        ApiService apiService = HKHttpUtils.getApiService();
        apiService.getAllOwnerClassify(MainActivity.ticket).enqueue(new HKResponseResultCallBack<List<LevelBean>>() {
            @Override
            public void onSuccess(List<LevelBean> levelBeans) {
                if (levelBeans != null && levelBeans.get(0) != null && levelBeans.get(0).getDescribe() != null){
                    Log.d(TAG, "onSuccess: "+levelBeans.get(0).getDescribe());

                    levelDataSource = levelBeans;
                    initDistrictPopupWindow();
                }else {
                    Log.d(TAG, "onSuccess: -===");
                }

            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                Log.d(TAG, "onGetDataFailed: "+msg);
            }

            @Override
            public void onFailed(Call call, Throwable t) {
                Log.d(TAG, "onFailed: "+t.getMessage());
            }
        });
    }


    private void initDeleteTagDialog(){
        deleteTagDialog = new Dialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.delete_tag_dialog, null);

        deleteTagTextView = contentView.findViewById(R.id.delete_tag_name);
        deleteTagDialog.setContentView(contentView);
        deleteTagDialog.setCanceledOnTouchOutside(false);
        deleteTagDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        contentView.findViewById(R.id.close_dialog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dismissDeleteTagDialog();
            }
        });
        contentView.findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(deleteType) || TextUtils.isEmpty(deleteTag) || -1 == deletePosition){
                    Toast.makeText(TagsActivity.this,"选择删除标签失败，请重新选择",Toast.LENGTH_LONG).show();
                    return;
                }
                deleteTag();
            }
        });
    }

    public void initDistrictPopupWindow() {

        int option1 = 0;
        int option2 = 0;
        ArrayList<String> levelStringList = new ArrayList<>();
        ArrayList<List<String>> detailLevelStringList = new ArrayList<>();
        ArrayList<String> detailStringList;
        for (LevelBean levelBean : levelDataSource){


            levelStringList.add(levelBean.getDescribe());
            detailStringList = new ArrayList<>();
            for (LevelBean l : levelBean.getSubLevelClassify()){
                detailStringList.add(l.getDescribe());

            }
            detailLevelStringList.add(detailStringList);
        }


        for (int i = 0 ; i < levelDataSource.size() ; i ++){
            if (levelDataSource.get(i).getLevel().equals(levelKey)){
                option1 = i;
                for (int j = 0 ; j < levelDataSource.get(i).getSubLevelClassify().size() ; j ++){
                    if (levelDataSource.get(i).getSubLevelClassify().get(j).getLevel().equals(detailLevelKey)){
                        option2 = j;
                        break;
                    }
                }
                break;
            }
        }
        Log.d(TAG, "initDistrictPopupWindow: "+option1);
        Log.d(TAG, "initDistrictPopupWindow: "+option2);




        pickerView = new OptionsPickerView(this);
        pickerView.setPicker(levelStringList,detailLevelStringList,true);
        pickerView.setCyclic(false);
        pickerView.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                Log.d(TAG, "onOptionsSelect: "+options1);
                Log.d(TAG, "onOptionsSelect: "+option2);
                Log.d(TAG, "onOptionsSelect: "+levelDataSource.get(options1).getDescribe());
                Log.d(TAG, "onOptionsSelect: "+levelDataSource.get(options1).getSubLevelClassify().get(option2).getDescribe());
                selectLevel = levelDataSource.get(options1);
                selectDetailLevel = levelDataSource.get(options1).getSubLevelClassify().get(option2);
                saveLevel();
            }
        });
        pickerView.setSelectOptions(option1,option2);
    }


    private void saveLevel(){
        ApiService apiService = HKHttpUtils.getApiService();
        apiService.saveOwnerLevel(MainActivity.ticket,String.valueOf(ownerId),selectLevel.getLevel(),selectDetailLevel.getLevel()).enqueue(new HKResponseResultCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                levelTextView.setText(selectLevel.getDescribe());
                detailLevelTextView.setText(selectDetailLevel.getDescribe());
                Toast.makeText(TagsActivity.this,"保存成功",Toast.LENGTH_LONG);
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                Toast.makeText(TagsActivity.this,msg,Toast.LENGTH_LONG);
            }

            @Override
            public void onFailed(Call call, Throwable t) {
                Toast.makeText(TagsActivity.this,t.getMessage(),Toast.LENGTH_LONG);
            }
        });
    }

    @Override
    public void onDeleteItem(int position, View view) {
        TagListItemBean tagListItemBean = tagListItemBeans.get(position);
        String type = tagListItemBean.getType();
        String deleteType = "";
        if ("food".equals(type)){
            deleteType = "饮食喜好";
        }else if ("life".equals(type)){

            deleteType = "生活习惯";
        }else if ("hobby".equals(type)){
            deleteType = "特长爱好";

        }else if ("other".equals(type)){

            deleteType = "其他";
        }
        if (TextUtils.isEmpty(deleteType)){
            Toast.makeText(this,"无法获取分类，删除失败",Toast.LENGTH_LONG).show();
            return;
        }

        String tag = tagListItemBean.getContent();
        if (TextUtils.isEmpty(tag)){
            Toast.makeText(this,"无法获取标签，删除失败",Toast.LENGTH_LONG).show();
            return;
        }
        if (deleteTagDialog == null){
            initDeleteTagDialog();
        }
        this.deleteType = deleteType;
        this.deleteTag = tag;
        this.deletePosition = position;
        deleteTagTextView.setText(Html.fromHtml("确认删除<font color='#EA5404'>"+deleteTag+"</font>标签"));
        deleteTagDialog.show();

    }

  /*  @OnClick({R.id.back,R.id.add_tag_button,R.id.level,R.id.detail_level})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.back:
                dismissAddTagDialog();
                dismissDeleteTagDialog();
                setResult(RESULT_OK);
                finish();
                break;
            case R.id.add_tag_button:
                if (addTagDialog == null){
                    initAddTagDialog();
                }
                addTagDialog.show();
                break;
            case R.id.level:
                if (pickerView == null && levelDataSource != null && levelDataSource.size() > 0){
                    initDistrictPopupWindow();
                    pickerView.show();
                }else if (pickerView != null && !pickerView.isShowing()){
                    pickerView.show();
                }else {
                    Toast.makeText(this,"暂无等级信息",Toast.LENGTH_LONG);
                }

                break;
            case R.id.detail_level:
                if (pickerView == null && levelDataSource != null && levelDataSource.size() > 0){
                    initDistrictPopupWindow();
                    pickerView.show();
                }else if (pickerView != null && !pickerView.isShowing()){
                    pickerView.show();
                }else {
                    Toast.makeText(this,"暂无等级信息",Toast.LENGTH_LONG);
                }
                break;
            default:
                break;
        }
    }
*/
    private void addTag(String selectTagType , String tag){
        if (ownerId != -1) {
            ApiService apiService = HKHttpUtils.getApiService();
            apiService.addTag(MainActivity.ticket, ownerId,selectTagType,tag).enqueue(new HKResponseResultCallBack<Object>() {
                @Override
                public void onSuccess(Object o) {
                    getTagList();
                    Toast.makeText(TagsActivity.this,"添加成功",Toast.LENGTH_LONG).show();
                    dismissAddTagDialog();
                }

                @Override
                public void onGetDataFailed(int cd, String msg) {
                    Toast.makeText(TagsActivity.this,msg,Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFailed(Call call, Throwable t) {
                    Toast.makeText(TagsActivity.this,"网络连接失败，请稍后再试",Toast.LENGTH_LONG).show();
                }
            });
        }else {
            Toast.makeText(this,"获取用户ID失败",Toast.LENGTH_LONG).show();
        }
    }

    private void deleteTag(){
        if (ownerId != -1){
            ApiService apiService = HKHttpUtils.getApiService();
            apiService.deleteTag(MainActivity.ticket, ownerId,deleteType,this.deleteTag).enqueue(new HKResponseResultCallBack<Object>() {
                @Override
                public void onSuccess(Object object) {
                    deleteTagTitle(deleteType,deleteTag,deletePosition);
                    mAdatper.notifyDataSetChanged();
                    dismissDeleteTagDialog();
                    Toast.makeText(TagsActivity.this,"删除成功",Toast.LENGTH_LONG).show();
                }

                @Override
                public void onGetDataFailed(int cd, String msg) {
                    Toast.makeText(TagsActivity.this,msg,Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFailed(Call call, Throwable t) {
                    Toast.makeText(TagsActivity.this,"网络连接失败，请稍后再试",Toast.LENGTH_LONG).show();
                }
            });
        }else {
            Toast.makeText(this,"获取用户ID失败",Toast.LENGTH_LONG).show();
        }
    }

    private void deleteTagTitle(String selectTagType,String tag,int position){
        List<TagBean> foodList = mListTagBean.getFood();
        List<TagBean> lifeList = mListTagBean.getLife();
        List<TagBean> hobbyList = mListTagBean.getHobby();
        List<TagBean> otherList = mListTagBean.getOther();
        if ("饮食喜好".equals(selectTagType)){

            if (mListTagBean != null && foodList != null && foodList.size() != 0) {
                for (int i = 0; i < foodList.size(); i++) {
                    if (tag.equals(foodList.get(i).getTagName2())) {
                        foodList.remove(i);
                    }
                }
                if (foodList.size() == 0){
                    for (int j = 0 ; j < tagListItemBeans.size() ; j++){
                        if ("title".equals(tagListItemBeans.get(j).getType()) && "饮食喜好".equals(tagListItemBeans.get(j).getContent())){
                            tagListItemBeans.remove(j);
                            tagListItemBeans.remove(position-1);
                        }
                    }
                }else {
                    tagListItemBeans.remove(position);
                }
            }


        }else if ("生活习惯".equals(selectTagType)){
            if (mListTagBean != null && lifeList != null && lifeList.size() != 0) {
                for (int i = 0; i < lifeList.size(); i++) {
                    if (tag.equals(lifeList.get(i).getTagName2())) {
                        lifeList.remove(i);
                    }
                }
                if (lifeList.size() == 0){
                    for (int j = 0 ; j < tagListItemBeans.size() ; j++){
                        if ("title".equals(tagListItemBeans.get(j).getType()) && "生活习惯".equals(tagListItemBeans.get(j).getContent())){
                            tagListItemBeans.remove(j);
                            tagListItemBeans.remove(position-1);
                        }
                    }
                }else {
                    tagListItemBeans.remove(position);
                }
            }
        }else if ("特长爱好".equals(selectTagType)){
            if (mListTagBean != null && hobbyList != null && hobbyList.size() != 0) {
                for (int i = 0; i < hobbyList.size(); i++) {
                    if (tag.equals(hobbyList.get(i).getTagName2())) {
                        hobbyList.remove(i);
                    }
                }
                if (hobbyList.size() == 0){
                    for (int j = 0 ; j < tagListItemBeans.size() ; j++){
                        if ("title".equals(tagListItemBeans.get(j).getType()) && "特长爱好".equals(tagListItemBeans.get(j).getContent())){
                            tagListItemBeans.remove(j);
                            tagListItemBeans.remove(position-1);
                        }
                    }
                }else {
                    tagListItemBeans.remove(position);
                }
            }
        }else if ("其他".equals(selectTagType)){
            if (mListTagBean != null && otherList != null && otherList.size() != 0) {
                for (int i = 0; i < otherList.size(); i++) {
                    if (tag.equals(otherList.get(i).getTagName2())) {
                        otherList.remove(i);
                    }
                }
                if (otherList.size() == 0){
                    for (int j = 0 ; j < tagListItemBeans.size() ; j++){
                        if ("title".equals(tagListItemBeans.get(j).getType()) && "其他".equals(tagListItemBeans.get(j).getContent())){
                            tagListItemBeans.remove(j);
                            tagListItemBeans.remove(position-1);
                        }
                    }
                }else {
                    tagListItemBeans.remove(position);
                }
            }
        }else {

        }


        if (tagListItemBeans == null || tagListItemBeans.size() == 0){
            empty_tag.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        }
    }


    private void getTagList(){
        if (ownerId != -1){
            ApiService apiService = HKHttpUtils.getApiService();
            apiService.getTagList(MainActivity.ticket,ownerId).enqueue(new HKResponseResultCallBack<ListTagBean>() {
                @Override
                public void onSuccess(ListTagBean listTagBean) {
                    mListTagBean = listTagBean;
                    tagListItemBeans.clear();
                    tagListItemBeans.addAll(assembleData(listTagBean));
                    mAdatper.notifyDataSetChanged();
                    if (tagListItemBeans!= null && tagListItemBeans.size() != 0){
                        empty_tag.setVisibility(View.GONE);
                        mRecyclerView.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onGetDataFailed(int cd, String msg) {
                    Toast.makeText(TagsActivity.this,msg,Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFailed(Call call, Throwable t) {
                    Toast.makeText(TagsActivity.this,"网络连接失败，请稍后再试",Toast.LENGTH_LONG).show();
                }
            });
        }else {
            Toast.makeText(this,"获取用户ID失败",Toast.LENGTH_LONG).show();
        }
    }

    private List<TagListItemBean> assembleData(ListTagBean listTagBean){
        List<TagListItemBean> result = new ArrayList<>();
        //food
        if (listTagBean.getFood() != null && listTagBean.getFood().size() != 0){
            result.add(new TagListItemBean("title","饮食喜好"));
            for (int i = 0 ; i < listTagBean.getFood().size() ; i ++){
                result.add(new TagListItemBean("food",listTagBean.getFood().get(i).getTagName2()));
            }
        }

        //life
        if (listTagBean.getLife() != null && listTagBean.getLife().size() != 0){
            result.add(new TagListItemBean("title","生活习惯"));
            for (int i = 0 ; i < listTagBean.getLife().size() ; i ++){
                result.add(new TagListItemBean("life",listTagBean.getLife().get(i).getTagName2()));
            }
        }

        if (listTagBean.getHobby() != null && listTagBean.getHobby().size() != 0){
            result.add(new TagListItemBean("title","特长爱好"));
            //food
            for (int i = 0 ; i < listTagBean.getHobby().size() ; i ++){
                result.add(new TagListItemBean("hobby",listTagBean.getHobby().get(i).getTagName2()));
            }
        }

        if (listTagBean.getPet() != null && listTagBean.getPet().size() != 0){
            result.add(new TagListItemBean("title","养宠状态"));
            //food
            for (int i = 0 ; i < listTagBean.getPet().size() ; i ++){
                result.add(new TagListItemBean("pet",listTagBean.getPet().get(i).getTagName2()));
            }
        }

        if (listTagBean.getOther() != null && listTagBean.getOther().size() != 0){
            result.add(new TagListItemBean("title","其他"));
            //food
            for (int i = 0 ; i < listTagBean.getOther().size() ; i ++){
                result.add(new TagListItemBean("other",listTagBean.getOther().get(i).getTagName2()));
            }
        }

        return result;

    }

    private void dismissAddTagDialog(){
        if (addTagDialog != null && addTagDialog.isShowing()){
            radioGroup.clearCheck();
            inputTag.setText("");
            addTagDialog.dismiss();
        }
    }

    private void dismissDeleteTagDialog(){
        if (deleteTagDialog != null && deleteTagDialog.isShowing()){
            this.deleteType = null;
            this.deleteTag = null;
            this.deletePosition = -1;
            deleteTagDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissAddTagDialog();
        dismissDeleteTagDialog();
        addTagDialog = null;
        deleteTagDialog = null;
        if (pickerView != null && pickerView.isShowing()){
            pickerView.dismiss();
            pickerView = null;
        }
    }
}
